package cn.edu.bupt.ch6_1.controller;

import cn.edu.bupt.ch6_1.common.Result;
import cn.edu.bupt.ch6_1.entity.Product;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@Tag(name = "向购物车添加商品(Redis版)")
@RestController
@RequestMapping("/api/v1/product")
public class ProductController {

    final
    RedisTemplate redisTemplate;

    public ProductController(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Operation(summary = "获取商品列表", description = "返回值为全部的商品列表")
    @GetMapping(path = "/", produces = "application/json")
    public Result<?> listAll() {
        //List<Product> products = redisTemplate.opsForList().range("product:list",0,-1);
        BoundListOperations boundListOperations = redisTemplate.boundListOps("product:list");
        List<Product> products = boundListOperations.range(0,-1);
        return Result.ok(products);
    }


    @Operation(summary = "添加新的商品", description = "创建成功，返回状态码201")
    @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
    public Result<?> add(@RequestBody Product product) {
        redisTemplate.opsForList().rightPush("product:list",product);
        return Result.ok(product);
    }

    @Operation(summary = "删除最先添加的商品", description = "如果不存在，则返回状态码404")
    @DeleteMapping(path = "/left")
    public Result<?> deleteLeft() {
        Product product = (Product)redisTemplate.opsForList().leftPop("product:list");
        if (product!= null) {
            return Result.ok(product);
        } else {
            return Result.error(404, "商品不存在");
        }
    }

    @Operation(summary = "删除最后添加的商品", description = "如果不存在，则返回状态码404")
    @DeleteMapping(path = "/right")
    public Result<?> deleteRight() {
        Product product = (Product)redisTemplate.opsForList().rightPop("product:list");
        if (product!= null) {
            return Result.ok(product);
        } else {
            return Result.error(404, "商品不存在");
        }
    }

}
